package com.dingding.special.user.login.dao.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.daox.IBaseDaoX;
import com.dingding.common.core.base.daox.ICriteriaBaseDao;
import com.dingding.common.core.base.daox.ISQLBaseDao;
import com.dingding.common.core.beans.special.SpecialOrderdesignateset;
import com.dingding.common.core.beans.special.SpecialUserloginrecord;
import com.dingding.common.core.beans.special.Specialuseraccount;
import com.dingding.common.core.beans.special.Specialuserinfo;
import com.dingding.common.core.beans.special.Specialuserlogin;
import com.dingding.common.core.beans.special.Specialuserposition;
import com.dingding.common.core.beans.special.Specialuservehicleinfo;
import com.dingding.common.core.config.ServiceCode;
import com.dingding.common.core.push.pushmsg.PushData;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.bean.BeanUtilx;
import com.dingding.facade.queue.dto.push.PushRequestDTO;
import com.dingding.facade.queue.enums.ClientType;
import com.dingding.facade.queue.enums.PushType;
import com.dingding.facade.queue.enums.RoleType;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.special.user.constans.UserInfoConstant;
import com.dingding.special.user.enums.userInfo.AppointOrderType;
import com.dingding.special.user.enums.userInfo.DepositSet;
import com.dingding.special.user.enums.userInfo.OutwardRunStatus;
import com.dingding.special.user.enums.userInfo.SpecialVehicleInfoStatus;
import com.dingding.special.user.enums.userInfo.UserAccountStatus;
import com.dingding.special.user.enums.userInfo.UserRole;
import com.dingding.special.user.enums.userInfo.UserSex;
import com.dingding.special.user.enums.userInfo.UserStatus;
import com.dingding.special.user.enums.userInfo.VehicleIsAuthStatus;
import com.dingding.special.user.enums.userInfo.VoiceAnnouncements;
import com.dingding.special.user.login.dao.IUserLoginDao;
import com.dingding.special.user.login.dao.sql.SpecialUserLoginSQL;
import com.dingding.special.user.login.dto.ReqSpecialUserLoginDTO;
import com.dingding.special.user.login.dto.ResSpecialUserLoginDTO;
import com.dingding.special.user.login.dto.UserSinglePointLoginPushDTO;

/**
 * 
 * @ClassName: UserLoginDaoImpl 
 * @Description: 用户登录DAO
 * @author CHEHAUNBO 
 * @date 2016年8月21日 下午3:36:19
 * 
 */
@Component("specialUserLoginDao")
public class UserLoginDaoImpl implements IUserLoginDao {

	@Resource(name = "criteriaBaseDao")
	private ICriteriaBaseDao criteriaBaseDao;

	@Resource(name = "SQLBaseDao")
	private ISQLBaseDao sqlBaseDao;

	@Resource(name = "baseDaoX")
	private IBaseDaoX baseDaoX;

	@Resource(name = "queueService")
	private IQueueFacade queueFacade;

	private static Logger log = Logger.getLogger(UserLoginDaoImpl.class);

	/**
	 * 
	 * 通过手机号获取获取用户登录信息
	 * 
	 * @Title: getUserLoginInfoByTelPhone
	 * @param telPhone 手机号
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public ResSpecialUserLoginDTO getUserLoginInfoByTelPhone(String telPhone) {

		try {
			if (ToolUtil.isNotBlank(telPhone)) {
				return sqlBaseDao.sqlToCustomBeanUnique(ResSpecialUserLoginDTO.class,
						SpecialUserLoginSQL.GET_USER_LOGININF, telPhone);
			}
		} catch (Exception e) {
			log.error("通过手机号获取获取用户登录信息出现异常！", e);
		}

		return null;
	}

	/**
	 * 
	 * 
	 * 首次登录，添加所有用户信息到DB中
	 * 
	 * @Title: addUserInfo
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public boolean addUserInfo(ResSpecialUserLoginDTO resSpecialUserLoginDTO,
			ReqSpecialUserLoginDTO specialUserLoginDTO) {

		String uuid = UUID.randomUUID().toString();

		try {

			Specialuserlogin specialuserlogin = createSpecialUserLogin(uuid, specialUserLoginDTO);
			Specialuserinfo specialuserinfo = createSpecialuserinfo(uuid, specialUserLoginDTO.getUserName());
			Specialuserposition specialuserposition = createSpecialuserposition(uuid,
					specialUserLoginDTO.getLoginCity());
			SpecialOrderdesignateset specialOrderdesignateset = createOrderdesignateset(uuid);
			Specialuseraccount specialuseraccount = createSpecialUserAccount(uuid);
			//Specialuservehicleinfo specialuservehicleinfo = createSpecialUserVehicleInfo(uuid);

			// 用户登录
			baseDaoX.save(specialuserlogin);
			// 用户详细信息
			baseDaoX.save(specialuserinfo);
			// 用户位置记录
			baseDaoX.save(specialuserposition);
			// 专车用户指单设置
			baseDaoX.save(specialOrderdesignateset);
			// 专车用户账户
			baseDaoX.save(specialuseraccount);
			// 专车车辆信息
			//baseDaoX.save(specialuservehicleinfo);

			BeanUtilx.copyProperties(resSpecialUserLoginDTO, specialuserlogin);
			BeanUtilx.copyProperties(resSpecialUserLoginDTO, specialuserinfo);
			BeanUtilx.copyProperties(resSpecialUserLoginDTO, specialOrderdesignateset);
			//BeanUtilx.copyProperties(resSpecialUserLoginDTO, specialuservehicleinfo);

			// 未认证车主
			resSpecialUserLoginDTO.setSuvStatus(0);
			
			// 保存用户登录记录信息
			saveUserLoginRecord(specialUserLoginDTO, uuid, 1);

			return true;

		} catch (Exception e) {
			log.error("首次登录，添加所有用户信息到DB中出现异常！", e);
			return false;
		}

	}

	/**
	 * 
	 * 获取用户信息，更改用户状态
	 * @Title: updateUserLoginInfo
	 * @param telPhone 手机号
	 * @return String userId 用户ID
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public String updateUserLoginInfo(ReqSpecialUserLoginDTO specialUserLoginDTO,
			ResSpecialUserLoginDTO resSpecialUserLoginDTO) {

		Criterion criterion = Restrictions.eq("userName", specialUserLoginDTO.getUserName());
		try {

			Specialuserlogin specialuserlogin = criteriaBaseDao.queryCriteriaListUnique(Specialuserlogin.class,
					criterion);
			
			specialuserlogin.setClientType(specialUserLoginDTO.getClientType());

			// 判断是否为同一台设备登录
			if (ToolUtil.isBlank(specialuserlogin.getImei()) || !specialuserlogin.getImei().equals(specialUserLoginDTO.getImei())
					&& specialuserlogin.getUserStatus() == 1) {

				// 推送Bean
				PushData pushData = new PushData();
				// 推送序号(时间戳)
				pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
				// 推送时间
				pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
				// 模块
				pushData.setModular(ServiceCode.USER_LOGIN);

				UserSinglePointLoginPushDTO singlePointLoginPushDTO = new UserSinglePointLoginPushDTO();
				singlePointLoginPushDTO.setDeviceType(specialUserLoginDTO.getClientType());
				singlePointLoginPushDTO.setLogintime(new Date());
				pushData.setResponseBody(singlePointLoginPushDTO);

				PushRequestDTO pushRequestDTO = new PushRequestDTO();
				pushRequestDTO.setAliasId(specialuserlogin.getAliasId());
				pushRequestDTO.setRoleType(RoleType.Driver);
				ClientType clientType = ClientType.Android;
				if (specialuserlogin.getClientType() == "iOS") {
					clientType = ClientType.iOS;
				}
				pushRequestDTO.setPushType(PushType.msgcontent);
				pushRequestDTO.setClientType(clientType);
				pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));
				queueFacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));
			}

			BeanUtilx.copyProperties(specialuserlogin, specialUserLoginDTO);
			// 设置用户登录状态为已登录状态
			specialuserlogin.setUserStatus(UserStatus.login.getValue());

			// 保存用户登录记录信息
			saveUserLoginRecord(specialUserLoginDTO, specialuserlogin.getSuid(), 1);

			// 更新用户的aliasId极光推送id
			String newAliasId = ToolUtil.getUid();
			specialuserlogin.setAliasId(newAliasId);
			resSpecialUserLoginDTO.setAliasId(newAliasId);
			
			// 认证状态   0:未认证 1：审核中2：审核通过3：审核未通过 4：重新认证 5：审核资料过期
			if(resSpecialUserLoginDTO.getSuvStatus() == null){
				resSpecialUserLoginDTO.setSuvStatus(0);
			}

			return specialuserlogin.getSuid();

		} catch (Exception e) {
			log.error("用户登录获取用户登录信息出现异常！", e);
			return null;
		}

	}

	/**
	 * 
	 * 创建用户登录信息保存bean
	 * 
	 * @Title: createSpecialUserLogin 
	 * @param specialUserLoginDTO
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	private Specialuserlogin createSpecialUserLogin(String userId, ReqSpecialUserLoginDTO specialUserLoginDTO) {

		Specialuserlogin specialuserlogin = new Specialuserlogin();

		specialuserlogin.setSuid(userId); // 主键ID
		specialuserlogin.setAliasId(ToolUtil.getUid()); // 用户ID
		specialuserlogin.setUserName(specialUserLoginDTO.getUserName()); // 手机号
		specialuserlogin.setUserStatus(UserStatus.login.getValue()); // 用户状态
		specialuserlogin.setUserRole(UserRole.nodriver.getValue()); // 用户角色
		specialuserlogin.setIsDeposit(DepositSet.no.getValue()); // 是否设置过提现密码
		specialuserlogin.setClientType(specialUserLoginDTO.getClientType()); // 客户端类型
		specialuserlogin.setLoginCity(specialUserLoginDTO.getLoginCity());// 登录城市
		specialuserlogin.setClientVersion(specialUserLoginDTO.getAppVersion()); // app版本号
		specialuserlogin.setImei(specialUserLoginDTO.getImei());// 手机设备出厂标识
		specialuserlogin.setLastLoginTime(new Date());
		specialuserlogin.setCreateTime(new Date());
		specialuserlogin.setDepositNumber(0); // 当日提现次数

		return specialuserlogin;

	}

	/**
	 * 
	 * 创建用户详细信息
	 * 
	 * @Title: createSpecialuserinfo 
	 * @param userId 用户ID 
	 * @param telPhone 手机号
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	private Specialuserinfo createSpecialuserinfo(String userId, String telPhone) {

		Specialuserinfo specialuserinfo = new Specialuserinfo();
		specialuserinfo.setSuId(UUID.randomUUID().toString()); // 主键ID
		specialuserinfo.setUserId(userId); // 用户ID
		specialuserinfo.setNickName(UserInfoConstant.DEFAULT_USER_NICKNAME); // 用户昵称
		specialuserinfo.setAge(0); // 年龄
		specialuserinfo.setSex(UserSex.noset.getValue()); // 性别
		specialuserinfo.setUserTabloidAvatar(UserInfoConstant.DEFAULT_TABLOID_USERAVATAR); // 用户缩略头像
		specialuserinfo.setUserAvatar(UserInfoConstant.DEFAULT_USERAVATAR);// 用户头像
		specialuserinfo.setTelPhone(telPhone); // 手机号
		specialuserinfo.setUserLevel(new BigDecimal(5)); // 级
		
		//新添加字段
		specialuserinfo.setOrigin(UserInfoConstant.DEFAULT_STRING);
		specialuserinfo.setOccupation(UserInfoConstant.DEFAULT_STRING);
		
//		specialuserinfo.setTrueName(UserInfoConstant.DEFAULT_STRING);
//		specialuserinfo.setIdCard(UserInfoConstant.DEFAULT_STRING);
//		specialuserinfo.setIdCardPositiveImage(UserInfoConstant.DEFAULT_STRING);
//		specialuserinfo.setIdCardOppositeImage(UserInfoConstant.DEFAULT_STRING);
//		specialuserinfo.setJszImage(UserInfoConstant.DEFAULT_STRING);
//		specialuserinfo.setJszCopyImage(UserInfoConstant.DEFAULT_STRING);
//		specialuserinfo.setJszValidityPeriod(new Date());
//		specialuserinfo.setPermittedType(UserInfoConstant.DEFAULT_STRING);
//		specialuserinfo.setDriving(UserInfoConstant.DEFAULT_INTEGER);
//		specialuserinfo.setJszLssueDate(new Date());
//		specialuserinfo.setJszFileNumber(UserInfoConstant.DEFAULT_STRING);
		
		return specialuserinfo;

	}

	/**
	 *
	 * 创建用户位置初始化数据
	 * @Title: createSpecialuserposition 
	 * @param uesreId 用户ID
	 * @param currentCity 城市
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	private Specialuserposition createSpecialuserposition(String userId, String currentCity) {

		Specialuserposition specialuserposition = new Specialuserposition();
		specialuserposition.setSupId(UUID.randomUUID().toString()); // 主键ID
		specialuserposition.setUserId(userId); // 用户ID
		specialuserposition.setCurrentCity(currentCity); // 当前城市
		specialuserposition.setLongitude(0d); // 经度
		specialuserposition.setLatitude(0d);// 纬度
		specialuserposition.setSupStatus(OutwardRunStatus.close.getValue()); // 状态
		specialuserposition.setOutwardRunTime(new Date()); // 出车时间
		specialuserposition.setOnlineDuration(new BigDecimal(0)); // 当日在线时长

		return specialuserposition;

	}

	/**
	 * 
	 * 创建用户指单初始化数据
	 * 
	 * @Title: createOrderdesignateset 
	 * @param userId 用户ID
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	private SpecialOrderdesignateset createOrderdesignateset(String userId) {

		SpecialOrderdesignateset specialOrderdesignateset = new SpecialOrderdesignateset();
		specialOrderdesignateset.setOdsId(UUID.randomUUID().toString()); // 主键ID
		specialOrderdesignateset.setUserId(userId);// 用户ID
		specialOrderdesignateset.setAppointOrderType(AppointOrderType.All.getValue()); // 指派类型
		specialOrderdesignateset.setVoiceAnnouncements(VoiceAnnouncements.Yes.getValue()); // 语音播报
		specialOrderdesignateset.setDistanceFilter(new BigDecimal(5)); // 距离筛选，默认5公里
		specialOrderdesignateset.setSetTime(new Date()); // 设置时间

		return specialOrderdesignateset;

	}

	/**
	 * 
	 * 创建专车用户账户初始化数据
	 * 
	 * @Title: createSpecialUserAccount 
	 * @param userId 用户ID
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	private Specialuseraccount createSpecialUserAccount(String userId) {

		Specialuseraccount specialuseraccount = new Specialuseraccount();
		specialuseraccount.setUaId(UUID.randomUUID().toString()); // 用户ID
		specialuseraccount.setUserId(userId); // 用户ID
		specialuseraccount.setCurrencyAmount(new BigDecimal("0")); // 余额
		specialuseraccount.setSysFreezeCashAmount(new BigDecimal("0")); // 系统冻结金额
		specialuseraccount.setFreezeCashAmount(new BigDecimal("0")); // 提现冻结金额
		specialuseraccount.setAccountStatus(UserAccountStatus.regular.getValue());
		return specialuseraccount;

	}

	/**
	 * 
	 * 创建专车车辆信息
	 * 
	 * @Title: createSpecialUserVehicleInfo 
	 * @param userId 用户ID 
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	private Specialuservehicleinfo createSpecialUserVehicleInfo(String userId) {

		Specialuservehicleinfo specialuservehicleinfo = new Specialuservehicleinfo();
		specialuservehicleinfo.setUvId(UUID.randomUUID().toString()); // 主键ID
		specialuservehicleinfo.setUserId(userId); // 用户ID
		specialuservehicleinfo.setSuvStatus(SpecialVehicleInfoStatus.NoSubmit.getValue()); // 认证状态
		specialuservehicleinfo.setIsAuth(VehicleIsAuthStatus.No.getValue()); // 是否认证过
		
		// 新增字段
		specialuservehicleinfo.setLisencePlate(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setVehicleModel(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setVehicleType(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setVehicleColor(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setXszImage(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setVehicleImage(UserInfoConstant.DEFAULT_STRING);
		//specialuservehicleinfo.setJszValidityPeriod(new Date());
		specialuservehicleinfo.setSubmitTime(new Date());
		specialuservehicleinfo.setThroughTime(new Date());
		specialuservehicleinfo.setJszDescription(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setXszDescription(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setVehicleDescription(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setDescription(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setAuthType(VehicleIsAuthStatus.No.getValue());
		specialuservehicleinfo.setVehicleNumber(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setVehicleOwner(UserInfoConstant.DEFAULT_STRING);
		//specialuservehicleinfo.setXszCopyImage(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setXszLssueDate(new Date());
		specialuservehicleinfo.setWorkLicenseImage(UserInfoConstant.DEFAULT_STRING);
		specialuservehicleinfo.setWorkLicenseNumber(UserInfoConstant.DEFAULT_STRING);
		
		return specialuservehicleinfo;

	}

	/**
	 * 
	 * 保存用户登录记录信息
	 * 
	 * @Title: saveUserLoginRecord 
	 * @param userId 用户ID
	 * @param type 操作类型  登录 or 退出
	 * @author CHEHAUNBO
	 * @since V2.4.0
	 * 
	 */
	@Override
	public void saveUserLoginRecord(ReqSpecialUserLoginDTO specialUserLoginDTO, String userId, int type) {

		SpecialUserloginrecord specialUserloginrecord = new SpecialUserloginrecord();
		specialUserloginrecord.setUlrId(ToolUtil.getUid()); // 主键ID
		specialUserloginrecord.setUserId(userId); // 用户ID
		specialUserloginrecord.setCreateTime(new Date()); // 创建时间
		specialUserloginrecord.setType(type); // 操作类型 登录 or 退出
		BeanUtilx.copyProperties(specialUserloginrecord, specialUserLoginDTO);
		try {
			criteriaBaseDao.save(specialUserloginrecord);
		} catch (Exception e) {
			log.error("保存用户登录记录信息出现异常！", e);
		}

	}

}
